#!/bin/python
# encoding=utf8
'''
镜像安装脚本
	包含镜像：
	1、python3.7镜像安装
	2、sanic镜像安装，
	3、user_api镜像安装

'''
import subprocess


sanic_git_url = 'https://gitee.com/zhangpengju/sanic'
user_api_git_url = 'https://gitee.com/zhangpengju/user_api'


#执行shell命令
def execute_cmd(cmd):
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    output, err = p.communicate()
    # 判断命令是否执行成功
    status = 1 if err else 0
    if status == 0:
        print('[SUCCESS] %s' % cmd)
    else:
        print('[ERROR] %s' % cmd)
        print(err)
    return status, output

#拉取git文件
def clone_file():
    
    execute_cmd('rm -rf sanic user_api')
    clone_sanic = 'git clone %s' % sanic_git_url
    execute_cmd(clone_sanic)
    clone_user_api = 'git clone %s' % user_api_git_url
    execute_cmd(clone_user_api)

#安装sanic镜像
def setup_sanic_images():
    cmd = 'docker images | grep sanic'
    result = execute_cmd(cmd)
    if result[1] == '':
        setup_sanic_images_cmd = 'docker build -t sanic -f ./sanic/dockerfile ./sanic'
        result = execute_cmd(setup_sanic_images_cmd)
        print('sanic镜像安装成功')
	return
    print('sanic镜像已经安装')

#安装user_api接口镜像
def setup_user_api_images():
    cmd = 'docker images | grep user_api'
    result = execute_cmd(cmd)
    if result[1] != '':
	execute_cmd('docker rmi -f user_api:latest')
	print('原始镜像移除')
    setup_user_api_images_cmd = 'docker build -t user_api -f ./user_api/dockerfile ./user_api'
    result = execute_cmd(setup_user_api_images_cmd)
    if result[0] != 0:
	print('安装user_api镜像时出现错误')
	return
    print('新的user_api镜像已经安装')



if __name__ == '__main__':
    clone_file()
    setup_sanic_images()
    setup_user_api_images()





